import json
import bottle
from pymongo import Connection
from datetime import datetime

config_file = open('config.json')
config = json.load( config_file )

class Mongo:
    
    def __init__(self):
        self.connection = Connection(config['mongo']['hostname'], config['mongo']['port'])
        self.db = self.connection[config['mongo']['database']]
    
    def list(self, name):
        return bottle.abort(501, name + " :: LIST not implemented yet")

    def find(self, table, field, value):
        entity = self.db[table].find_one({field:value, 'active':1}) 
        if not entity:
            return {}
        del entity['active']
        return entity

    def delete(self, table, parameters):
        parameters['active'] = 1
        entity = self.db[table].find_one(parameters)
        if not entity:
            return {}
        entity['active'] = 0
        print entity
        result = self.db[table].save(entity)
        print result
        return result

    def save(self, table, entity):        
        entity['timestamp'] = datetime.now()
        entity['active'] = 1
        try:
            self.db[table].save(entity)
            return 0
        except ValidationError as ve:
            return 1